package com.foton.logistic.base;


import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.foton.logistic.R;
import com.foton.logistic.listener.IOnCodeListener;
import com.foton.logistic.listener.IOnResultListener;
import com.foton.logistic.manager.ScreenManager;
import com.foton.logistic.manager.SystemBarTintManager;
import com.foton.logistic.manager.TaskManager;
import com.foton.logistic.model.CodeResult;
import com.foton.logistic.task.BaseTask;
import com.foton.logistic.task.DispatchTask;
import com.foton.logistic.task.ShowDialogTask;
import com.foton.logistic.task.TaskConstant;
import com.foton.logistic.util.BaseConstant;
import com.foton.logistic.util.BroadcastUtil;
import com.foton.logistic.util.OptionUtil;
import com.foton.logistic.util.net.HttpUtil;
import com.foton.logistic.util.tool.LogUtil;
import com.foton.logistic.util.tool.RegexUtil;
import com.foton.logistic.util.tool.StringUtil;
import com.umeng.analytics.MobclickAgent;

import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import butterknife.Optional;


public abstract class BaseActivity extends Activity {
    public String taskTag = "BaseActivity";//当前BaseActivity的线程标识
    protected ScreenManager screenManager = ScreenManager.getScreenManagerInstance();
    public TaskManager taskManager = TaskManager.getTaskManagerInstance();
    @Optional
    @InjectView(R.id.base_ui_title_back_layout)
    public LinearLayout backLayout;
    @Optional
    @InjectView(R.id.base_ui_title_title)
    public TextView titleText;
    @Optional
    @InjectView(R.id.base_view_contain_layout)
    public LinearLayout containLayout;
    @Optional
    @InjectView(R.id.base_view_link_load)
    public LinearLayout loadLayout;
    @Optional
    @InjectView(R.id.base_ui_title_add_layout)
    public LinearLayout addLayout;
    IOnCodeListener iOnCodeListener;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        screenManager.pushActivity(this);
    }

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        ButterKnife.inject(this);
        setKitKatTranslucency();
        init();
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(taskTag);
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(taskTag);
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onDestroy() {
        cancelTasks();
        super.onDestroy();
    }

    /**
     * 初始化相关操作
     */
    public abstract void init();

    /**
     * 添加线程到线程管理中
     *
     * @param task
     */
    protected void addTask(BaseTask task) {
        try {
            taskManager.addTask(taskTag, task);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    /**
     * 关闭当前Activity中所有还在运行的线程
     */
    protected void cancelTasks() {
        taskManager.cancelLimitTasks(taskTag);
    }

    /**
     * 关闭当前Activity
     */
    public void finishSelf() {
        try {
            screenManager.closeActivity(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取线程标识
     *
     * @return
     */
    public String getTaskTag() {
        return taskTag;
    }

    /**
     * 设置线程标识
     *
     * @param taskTag
     */
    public void setTaskTag(String taskTag) {
        this.taskTag = taskTag;
    }

    @Optional
    @OnClick(R.id.base_choose_images_title_back)
    public void onBack() {
        finishSelf();
    }

    @Optional
    @OnClick(R.id.base_ui_title_back_layout)
    public void back() {
        OptionUtil.closeKeyBoard(this);
        finishSelf();
    }

    //	public void setBackLayoutVisibility(int visible){
//		backLayout.setVisibility(visible);
//	}
    public void setTitleText(String name) {
        this.titleText.setText(name);
    }

    public void setBackLayoutVisibility(int visible) {
        backLayout.setVisibility(visible);
    }

    public void setTitleTextVisibility(int visible) {
        titleText.setVisibility(visible);
    }
    public void setTitleAddVisibility(int visible) {
        addLayout.setVisibility(visible);
    }

    public void setKitKatTranslucency() {
        applyKitKatTranslucency(R.color.title_color);
    }

    /**
     * Apply KitKat specific translucency.
     */
    public void applyKitKatTranslucency(int colorId) {
        // KitKat translucent navigation/status bar.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setTranslucentStatus(true);
            SystemBarTintManager mTintManager = new SystemBarTintManager(this);
            mTintManager.setStatusBarTintEnabled(true);
            mTintManager.setNavigationBarTintEnabled(true);
            mTintManager.setTintResource(colorId);
            mTintManager.setStatusBarTintResource(colorId);
            mTintManager.setNavigationBarTintResource(colorId);
        }
    }

    @TargetApi(19)
    private void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    protected void startIntent(Class aClass) {
        startIntent(aClass, null);
    }

    protected void startIntent(Class aClass, Bundle bundle) {
        Intent intent = new Intent(this, aClass);
        if (null != bundle) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    protected Bundle getBundle(){
        return getIntent().getExtras();
    }

    /**
     * 显示键盘
     */
    @SuppressWarnings("static-access")
    protected void showSoftInput(EditText et) {
        et.setFocusable(true);
        et.setFocusableInTouchMode(true);
        et.requestFocus();
        InputMethodManager imm = (InputMethodManager) getSystemService(this.INPUT_METHOD_SERVICE);
        imm.showSoftInput(et, 0);
    }

    /**
     * 隐藏键盘
     */
    @SuppressWarnings("static-access")
    protected void hideSoftInput(EditText et) {
        InputMethodManager imm = (InputMethodManager) getSystemService(this.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(et.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
//            et.clearFocus();
    }
    //短信验证
    @Optional
    @InjectView(R.id.ft_include_confirm_code_send)
    public TextView confirmBtn;
    public boolean canLoanConfirm = true;
    private Handler confirmHandler;
    private Timer confirmTimer;
    private int confirmSeconds = BaseConstant.TIMER_SECONDS;
    public String confirmTel = "";
    public String saveTel = "";
    public String confirmCodeType = "1";
    public String confirmHttpUrl = BaseConstant.CONFIRMWORD;

    public void setConfirmTel(String confirmTel) {
        this.confirmTel = confirmTel;
    }

    public void setConfirmCodeType(String confirmCodeType) {
        this.confirmCodeType = confirmCodeType;
    }

    public void setConfirmHttpUrl(String confirmHttpUrl) {
        this.confirmHttpUrl = confirmHttpUrl;
    }
    public void showConfirmStatus(boolean normal) {
        if (confirmBtn != null) {
            if (normal) {
                confirmBtn.setSelected(false);
                canLoanConfirm = true;
            } else {
                confirmBtn.setSelected(true);
                canLoanConfirm = false;
            }
        }
    }

    @Optional
    @OnClick(R.id.ft_include_confirm_code_send)
    public void changeConfirmWord() {
        //if(!StringUtil.isEmpty(confirmTel)){
		/*	if (confirmTel.equals(BaseConstant.userDataEntity.selfInfo.phone)){
				OptionUtil.addToast(this, "请修改手机号");
				return;
			} else*/
	/*	if (SharedUtil.getRegTel1(this).equals(confirmTel)){
            OptionUtil.addToast(this, "该手机号已注册");
            return;
        }*/
		if (StringUtil.isEmpty(confirmTel)){
            OptionUtil.addToast(this, "请更改手机号");
            return;
        }else if (!StringUtil.isEmpty(confirmTel)&&!RegexUtil.checkMobile(confirmTel)) {
            OptionUtil.addToast(this, "手机号格式不正确");
            return;
        }/*else if (confirmTel.equals(BaseConstant.userDataEntity.selfInfo.phone)){

				OptionUtil.addToast(this, "请修改手机号");
			}*/
		/*}else {
			OptionUtil.addToast(this, "请更换手机号");
		}*/

        getConfirmWord(confirmTel);
    }

    /**
     * 获取验证码
     *
     * @param tel
     */
    public String smsCode;

    public void getConfirmWord(String tel) {
        Map<String, Object> argMap = HttpUtil.getEncryMap();
        argMap.put("tel", tel);
        LogUtil.e("tel="+tel);
        argMap.put("type", confirmCodeType);
        LogUtil.e("++++++++"+argMap);
        ShowDialogTask task = new ShowDialogTask(this, taskTag, confirmBtn, getString(R.string.get_confirm_code), true, confirmHttpUrl, argMap, TaskConstant.POST);
        task.setParseClass(CodeResult.class);
        task.setiOnResultListener(new IOnResultListener() {
            @Override
            public void onOK(DispatchTask task) {
                CodeResult codeResult = (CodeResult)task.resultEntity;
                smsCode = codeResult.data.confirmCode;
                LogUtil.e("++++++++++++++++"+smsCode);
                saveTel=confirmTel;
                if (iOnCodeListener!=null){
                    iOnCodeListener.onCode(smsCode);
                }
                startMessageTimer();
            }

            @Override
            public void onError(DispatchTask task) {

            }

            @Override
            public void onDone(DispatchTask task) {

            }
        });
        task.execute();
    }

    public void setiOnCodeListener(IOnCodeListener iOnCodeListener) {
        this.iOnCodeListener = iOnCodeListener;
    }
    public void startMessageTimer() {
        confirmSeconds = BaseConstant.TIMER_SECONDS;
        TimerTask task = new TimerTask() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                confirmSeconds--;
                Message message = new Message();
                message.what = confirmSeconds;
                confirmHandler.sendMessage(message);
            }

        };
        confirmTimer = new Timer(true);
        confirmTimer.schedule(task, 100, 1000);
        confirmHandler = new Handler() {
            public void handleMessage(Message msg) {
                //activity
                try {
                    if (confirmBtn != null) {
                        if (msg.what <= 0) {
                            showConfirmStatus(true);
                            confirmBtn.setText("获取验证码");
                            confirmBtn.setClickable(true);
                            confirmTimer.cancel();
                            BroadcastUtil.sendEditEnble(BaseActivity.this, 0);
                        } else {
                            showConfirmStatus(false);
                            confirmBtn.setClickable(false);
                            confirmBtn.setText("" + msg.what + getResources().getString(R.string.get_confirm_code2));
                            BroadcastUtil.sendEditEnble(BaseActivity.this, 1);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
    }
}